package com.github.freewu.commons.libs;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import com.github.freewu.commons.http.HttpFileCallBack;
import com.github.freewu.commons.http.HttpUtils;
import com.lqkj.commons.R;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;

/**
 * 图标
 * Created by free on 16-5-20.
 */
public class IconView extends AppCompatTextView implements HttpFileCallBack{
    private Typeface typeface;

    private String url;

    private File fontPath;

    public IconView(Context context) {
        super(context);

        init(null);
    }

    public IconView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(attrs);
    }

    public IconView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(attrs);
    }
    private void init(AttributeSet attrs){
        if (attrs!=null){
            TypedArray a=getContext().obtainStyledAttributes(attrs, R.styleable.IconView);

            url=a.getString(R.styleable.IconView_url);

            if (!TextUtils.isEmpty(url)){
                File fontDir=getContext().getDir("font",Context.MODE_PRIVATE);

                fontPath= new File(fontDir,"iconfont.ttf");

                if (fontPath.exists() && fontPath.length()!=0){
                    typeface=Typeface.createFromFile(fontPath);
                }else{
                    if (!url.contains("http://")){
                        url="http://"+url;
                    }

                    HttpUtils.getInstance().downloadFile(url,fontPath,this);
                }
            }
        }
        if (typeface==null){
            typeface=Typeface.createFromAsset(getContext().getAssets(),"font/iconfont.ttf");
            setTypeface(typeface);
        }
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void onError(Call call, Exception e) {

    }

    @Override
    public void onSuccess(Call call, File downloadPath) {
        if (downloadPath.exists() && downloadPath.length()!=0) {
            typeface = Typeface.createFromFile(fontPath);

            setTypeface(typeface);

            requestLayout();
            invalidate();
        }
    }

    @Override
    public void onProgress(long progressByte, long allByte) {

    }
}
